import { _decorator, Color, Component, Label, Node, Sprite } from 'cc';
import { TraderEvent, TraderType } from '../entity/TraderEvent';
import { Utils } from '../common/Utils';
import { EventManager } from '../event/EventManager';
import { MapZone } from '../entity/MapZone';
import WorldManager from '../common/WorldManager';
import { UserInfo } from '../common/UserInfo';
const { ccclass, property } = _decorator;

@ccclass('Trader')
export class Trader extends Component {
    @property(Sprite)
    tittleBg: Sprite
    @property(Label)
    tittle: Label
    @property(Label)
    time: Label
    @property(Label)
    wood: Label
    @property(Label)
    mud: Label
    @property(Label)
    iron: Label
    @property(Label)
    food: Label


    private offTime:number = 0
    private eventData:TraderEvent
    start() {

    }

    setData(event: TraderEvent) {
        this.eventData = event

        let yellow = new Color('#C38E00')
        let green = new Color('#00C375')
        let coord = MapZone.getXyByZoneId(event.eZone, WorldManager.instance.radius)
        let x = coord[0]
        let y = coord[1]
        switch (event.etype) {
            case TraderType.From:
                this.tittleBg.color = yellow
                this.tittle.string = `向 ${event.eSimZoneName} ( ${x} | ${y} )运送`
                break
            case TraderType.Back:
                this.tittleBg.color = green
                this.tittle.string = `从 ${event.eSimZoneName} ( ${x} | ${y} )返回`
                break
            case TraderType.To:
                this.tittleBg.color = yellow
                this.tittle.string = `从 ${event.eZoneName} ( ${x} | ${y} )运来`
                break
        }

        this.wood.string = event.wood + ''
        this.mud.string = event.mud + ''
        this.iron.string = event.iron + ''
        this.food.string =  event.food + ''
        
        let now = Math.floor(UserInfo.instance.serverTime / 1000)
        this.offTime = Math.floor(event.eEnd)  - now
        console.log('offTime:',this.offTime)
        this.time.string = Utils.secondToStr(this.offTime)
        this.schedule(this.countDown, 1, this.offTime - 1)

        // 为了兼容服务端，返回了小于当前的时间
        this.emitEvent()
       
    }

    countDown(){
        this.offTime --
        this.time.string = Utils.secondToStr(this.offTime)
        this.emitEvent()
    }

    emitEvent(){
        if(this.offTime <=0 ){
            this.scheduleOnce(() => {
                EventManager.instance.emit(EventManager.EventType.TraderTimeDown, this.eventData)

                if(this.eventData.etype == TraderType.Back){
                    EventManager.instance.emit(EventManager.EventType.TraderBack, this.eventData)
                }
            }, 1)
        }
    }

}


